from django.shortcuts import render, reverse
from django.http import HttpResponse, JsonResponse
from .. import models


# Create your views here.
# 显示缩进和父类名
def selectAllTypes():
    # select *,concat(path,id) as paths from myadmin_booktype order by paths;
    data = models.Booktype.objects.extra(select={'paths': 'concat(path,id)'}).order_by('paths')
    for x in data:
        num = x.path.count(',') - 1
        x.sb = '|----' * num
        if x.pid != 0:
            x.pname = models.Booktype.objects.get(id=x.pid).name
    return data


# 后台图书分类列表
def index(request):
    # 获取所有的图书分类
    # data = models.Booktype.objects.all()
    data = selectAllTypes()
    context = {'data': data}
    return render(request, 'myadmin/types/index.html', context)


# 后台图书分类添加
def add(request):
    # 获取所有的图书分类
    data = selectAllTypes()
    context = {'data': data}
    return render(request, 'myadmin/types/add.html', context)


# 后台图书分类 执行添加
def insert(request):
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')
    # {'pid': '0', 'name': '教育'}
    # {'pid': '1', 'name': '教材',path="0,1"}
    if data['pid'] == '0':
        # 顶级分类
        data['path'] = '0,'
    else:
        # 子类
        # 查询当前选择的父类path
        path = models.Booktype.objects.get(id=data['pid']).path
        data['path'] = path + data['pid'] + ','
    # print(data)

    # 执行数据的添加
    try:
        obj = models.Booktype(**data)
        obj.save()
        url = reverse('myadmin_types_index')
        return HttpResponse(f'<script>alert("图书分类添加成功");location.href="{url}"</script>')
    except:
        url = reverse('myadmin_types_add')
        return HttpResponse(f'<script>alert("图书分类添加失败");location.href="{url}"</script>')


# 后台图书分类 删除
def delete(request):
    # 获取分类id
    id = request.GET.get('id')

    # 判断当前类下是否还有子类
    num = models.Booktype.objects.filter(pid=id).count()
    # print(num)
    if num:
        return JsonResponse({'code': 1, 'msg': '当前分类下还有子类,不能删除'})

    # 判断当前类下是否还有商品
    # if goodsnum:
    #     return JsonResponse({'code': 2, 'msg': '当前分类下还有商品,不能删除'})

    # 执行删除
    # 获取分类对象
    try:
        obj = models.Booktype.objects.get(id=id)
        obj.delete()
        return JsonResponse({'code': 0, 'msg': '删除成功'})
    except:
        return JsonResponse({'code': 3, 'msg': '删除失败'})


# 后台图书分类 编辑
def edit(request):
    try:
        id = request.GET.get('id')
        name = request.GET.get('name')

        obj = models.Booktype.objects.get(id=id)
        obj.name = name
        obj.save()
        return JsonResponse({'code': 0, 'msg': '更新成功'})
    except:
        return JsonResponse({'code': 1, 'msg': '更新失败'})

